package com.yq.front.service.impl;

import com.yq.api.comm.ResultHandle;
import com.yq.api.dto.UserTO;
import com.yq.api.exception.usr.AddUserException;
import com.yq.api.exception.usr.DeleteUserException;
import com.yq.api.exception.usr.UpdateUserException;
import com.yq.api.service.UserServiceFacade;
import com.yq.front.service.UserFrontService;
import com.yq.front.util.UserVOUtil;
import com.yq.front.vo.UserVO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by yq on 16-6-18.
 */
@Service("userFrontService")
public class UserFrontServiceImpl implements UserFrontService {
    @Resource(name = "userServiceFacade")
    private UserServiceFacade userServiceFacade;

    private static final Log log = LogFactory.getLog(UserFrontServiceImpl.class);

    public void addUser(UserVO userVO) {
        UserTO userTO = UserVOUtil.toUserTO(userVO);
        ResultHandle<UserTO> resultHandle = userServiceFacade.addUser(userTO);
        if(!resultHandle.getSuccess()){
            log.error(resultHandle.getMessage());
            throw new AddUserException(resultHandle.getMessage());
        }
    }

    public void deleteUser(UserVO userVO) {
        UserTO userTO = UserVOUtil.toUserTO(userVO);
        ResultHandle<UserTO> resultHandle = userServiceFacade.deleteUser(userTO);
        if(!resultHandle.getSuccess()){
            log.error(resultHandle.getMessage());
            throw new DeleteUserException(resultHandle.getMessage());
        }
    }

    public void updateUser(UserVO userVO) {
        UserTO userTO = UserVOUtil.toUserTO(userVO);
        ResultHandle<UserTO> resultHandle = userServiceFacade.updateUser(userTO);
        if(!resultHandle.getSuccess()){
            log.error(resultHandle.getMessage());
            throw new UpdateUserException(resultHandle.getMessage());
        }
    }

    public UserVO findUser(Long userId) {
        ResultHandle<UserTO> resultHandle = userServiceFacade.findUser(userId);
        if(!resultHandle.getSuccess()){
            log.error(resultHandle.getMessage());
            return null;
        }
        UserTO userTO = resultHandle.getResultContent();
        UserVO userVO = UserVOUtil.toUserVO(userTO);
        return userVO;
    }

    public List<UserVO> findUserList(UserVO userVO) {
        UserTO userTO = UserVOUtil.toUserTO(userVO);
        ResultHandle<List<UserTO>> resultHandle = userServiceFacade.getUserList(userTO);
        if(!resultHandle.getSuccess()){
            log.error(resultHandle.getMessage());
            return null;
        }
        List<UserVO> userVOList = UserVOUtil.toUserVOList(resultHandle.getResultContent());
        return userVOList;
    }
}
